package controller

import (
	"dlist/common/result"
	"dlist/issue"
	"dlist/utils/ptr"
	"dlist/web/domain"
	"dlist/web/mapper"
	"github.com/gin-gonic/gin"
	"strconv"
)

func AddIssue(c *gin.Context) {
	vo := domain.IssueVo{}
	err := c.BindJSON(&vo)
	if err != nil {
		domain.Fail(c, result.PARAMS_INVALID)
		return
	}
	issue.Manager.Create(ptr.Of(mapper.ToBo(vo)))
}

func DeleteIssue(c *gin.Context) {
	id, ok := getId(c)
	if !ok {
		return
	}
	issue.Manager.Delete(id)
}

func FinishIssue(c *gin.Context) {
	id, ok := getId(c)
	if !ok {
		return
	}
	issue.Manager.Finish(id)
}

func UndoFinishIssue(c *gin.Context) {
	id, ok := getId(c)
	if !ok {
		return
	}
	issue.Manager.UndoFinish(id)
}

func UpdateIssue(c *gin.Context) {
	vo := domain.IssueVo{}
	err := c.BindJSON(&vo)
	if err != nil {
		domain.Fail(c, result.PARAMS_INVALID)
		return
	}
	issue.Manager.Update(ptr.Of(mapper.ToBo(vo)))
}

func ListIssues(c *gin.Context) {
	issues := issue.Manager.List()
	domain.Success(c, mapper.BatchToVo(issues))
}

func GetIssue(c *gin.Context) {
	str := c.Query("id")
	id, _ := strconv.Atoi(str)
	issue := issue.Manager.GetByID(uint(id))
	domain.Success(c, mapper.ToVo(issue))
}

func getId(c *gin.Context) (uint, bool) {
	command := domain.IDCommand{}
	err := c.BindJSON(&command)
	if err != nil {
		domain.Fail(c, result.PARAMS_INVALID)
		return 0, false
	}
	return command.ID, true
}
